Validation #3: Number Check

This script will not submit unless the text field contains a number between 1 and 100.

Discussion

This form's onSubmit event calls the function validate() to check the values in the input field. If the value is unacceptable, the field is put in focus and the text selected to prepare for new text input.
function validate()
{
    // Version 3.0 will support
    // (typeof(parseInt(document.forms[0].F1.value)) == 'Number')
    // for now, we must assume that there is a number there
    // or else go through more elaborate parsing
    
    if (document.forms[0].F1.value.length == 0) 
    {
        alert('You must enter a number')
        return false
    }
    
    // Recover whatever value we can get
    var aValue = parseInt(document.forms[0].F1.value)
    if(isNaN(aValue))
        aValue = 0;
    
    // Check that it is in range.
    if ((aValue < 1) || (aValue > 100))
    {
        alert('Values must range between 1 and 100')
        
        // prepare field to be overwritten
        document.forms[0].F1.focus()
        document.forms[0].F1.select()
        return false
    }
    else 
        return true
}
Copyright ©2000 by Charles River Media, All Rights Reserved